<template>
  <div>
    <customContainer ref="customContainerRef" :config="config" />

    <el-dialog v-model="open1" title="处理问题件" :before-close="cancel1">
      <el-scrollbar class="myScrollbar">
        <el-timeline>
          <el-timeline-item v-for="(activity, index) in activities" :key="index" :timestamp="activity.operatingDate">
            <el-row style="background: #f3f6fd; padding: 10px; border-radius: 5px;">
              <el-col>【操作人】: {{ activity.operatingUser }} </el-col>
              <el-col>【状态描述】: {{ activity.statusEscription }} </el-col>
              <el-col>【地址描述】: {{ activity.addressDesc }}</el-col>
              <el-col>【备注】: {{ activity.remarks }}</el-col>
            </el-row>
          </el-timeline-item>
        </el-timeline>
      </el-scrollbar>
      <el-form
        ref="form1"
        style="margin-top: 20px;"
        :model="form"
      >
        <el-form-item label="状态说明" prop="statusEscription" :rules="[{ required: true, message: '必填', trigger: ['blur', 'change'] }]">
          <el-radio-group
            v-model="form.statusEscription"
          >
            <el-radio
              v-for="dict in feedbackStatus"
              :key="dict"
              style="width: 100px;margin: 0 20px;"
              :label="dict"
              @change="handleSelectStatus(dict)"
            >
              {{ dict }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          v-if="form.statusEscription == '客户资料提交情况'"
          :rules="form.statusEscription == '客户资料提交情况' ? [{ required: true, message: '必填', trigger: ['blur', 'change'] }] : []"
          label="地址说明"
          prop="addressDescList"
        >
          <el-select v-model="form.addressDescList" filterable multiple>
            <el-option
              v-for="dict in ['私人地址-调查表', '私人地址-备案号', '私人地址-未收到申明', '亚马逊地址-调查表', '亚马逊地址-未上传截图', '其他']"
              :key="dict"
              :label="dict"
              :value="dict"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remarks" :rules="form.addressDesc == '其他' ? [{ required: true, message: '必填', trigger: 'blur' }] : []">
          <el-input v-model="form.remarks" type="textarea" autosize></el-input>
        </el-form-item>
      </el-form>
      <div style="text-align: right;">
        <el-button type="primary" @click="submit">确定</el-button>
        <el-button type="info" @click="cancel1">取消</el-button>
      </div>
    </el-dialog>
    <el-dialog v-model="open2" title="批量处理问题件" :before-close="cancel2">
      <el-form
        ref="form2"
        style="margin-top: 20px;"
        :model="form"
      >
        <el-form-item label="状态说明" prop="statusEscription" :rules="[{ required: true, message: '必填', trigger: ['blur', 'change'] }]">
          <el-radio-group
            v-model="form.statusEscription"
          >
            <el-radio
              v-for="dict in feedbackStatus"
              :key="dict"
              :label="dict"
              style="width: 100px;margin: 0 20px;"
            >
              {{ dict }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          v-if="form.statusEscription == '客户资料提交情况'"
          :rules="form.statusEscription == '客户资料提交情况' ? [{ required: true, message: '必填', trigger: ['blur', 'change'] }] : []"
          label="地址说明"
          prop="addressDescList"
        >
          <el-select v-model="form.addressDescList" filterable multiple>
            <el-option
              v-for="dict in ['私人地址-调查表', '私人地址-备案号', '私人地址-未收到申明', '亚马逊地址-调查表', '亚马逊地址-未上传截图', '其他']"
              :key="dict"
              :label="dict"
              :value="dict"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remarks" :rules="form.addressDesc == '其他' ? [{ required: true, message: '必填', trigger: 'blur' }] : []">
          <el-input v-model="form.remarks" type="textarea" autosize></el-input>
        </el-form-item>
      </el-form>
      <div style="text-align: right;">
        <el-button type="primary" @click="submit2">确定</el-button>
        <el-button type="info" @click="cancel2">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { ref, getCurrentInstance, computed } from 'vue'
import { Download, Edit, Bottom } from '@element-plus/icons-vue'
import { ElButton, ElMessage } from 'element-plus'
import { DictDirection } from '@/store/modules/dicts'
import { listPiece, problemPieceDetails, handlingProblemPieces, downloadProblemPiece } from '@/api/order/problemPiece'
import userStore from '@/store/modules/user'

const user = userStore()
const username = user.user.nickName
// import { replaceParams } from '@/utils/regular';
// 选中数组
const customContainerRef = ref(null),
  // 非单个禁用
  single = ref(true),
  // 非多个禁用
  multiple = ref(true),
  {
    appContext: {
      config: {
        globalProperties: { $download, $validateForm },
      },
    },
  } = getCurrentInstance()

const form1 = ref(undefined)
const form2 = ref(undefined)
const open2 = ref(false)
const { proxy } = getCurrentInstance() as any
const open1 = ref(false)
// const addressDesc = ref([])
const activities = ref([])
const form = ref({
  statusEscription: '',
  feedbackStatus: '',
  operatingDate: '',
  internalRemarks: '',
  remarks: '',
  addressDescList: '',
  addressDesc: '',
  orderNos: '',
  subcontractNos: '',
}) 
const querys = ref({
  addressDescs: [],
  remarks: '',
  statusEscription: '',
  orderNos: '',
  subcontractNos: '',
  operatingUser: username,
})
const query2 = ref({
  addressDescs: [],
  remarks: '',
  statusEscription: '',
  orderNos: '',
  subcontractNos: '',
  operatingUser: username,
})

const feedbackStatus = ref(['客户已反馈', '已发邮件', '已回邮件', '客户资料提交情况', '已索赔', '已ups确认', '账号方确认', '已赔款', '已有索赔书', '跟踪进度记录'])
// 导出
const handleExport = () => {
  $download('order/problemPiece/problemPieceDetailsExport', { ...queryParams.value }, `problemPieceList_${ new Date().getTime() }.xlsx`)
}
// 批量处理问题件
const handleUpdates = () => {
  open2.value = true
}

const addressDesc = ref([])
const handleSelectStatus = (status) => {
  let list = []
  let list2 = []
  form.value.remarks = ''
  if (status == '客户资料提交情况') {
    list2 = activities.value
    .filter(el => el.statusEscription == status)
    .splice(-1, 1)
  }
  if (status == '跟踪进度记录' || status == '客户资料提交情况') {
    list = activities.value
    .filter(el => el.statusEscription == status)
    .splice(-1, 1)
  }
  if (list.length > 0) {
    list = list[0]
  }
  if (list2.length > 0) {
    list2 = list2[0].addressDesc.split(',')
    addressDesc.value = list2
  }
  // form.value.remarks = list.remarks
}
// 取消
const cancel1 = () => {
  open1.value = false
  proxy.$refs.form1.resetFields()
}
const cancel2 = () => {
  open2.value = false
  proxy.$refs.form2.resetFields()
}
const sid = ref([])
const oid = ref([])
// 处理问题件
const handleUpdate = (row: { [key: string]: any }) => {
  open1.value = true
  const subcontractNo = row.subcontractNo
  sid.value = row.subcontractNo
  oid.value = row.orderNo
  problemPieceDetails({ subcontractNo }).then((res) => {
    if (res.code == 200) {
      activities.value = res.data
    } else {
      ElMessage.error(res.msg)
    }
  })
}
// 确定
const submit = () => {
  query2.value.orderNos = [oid.value]
  query2.value.subcontractNos = [sid.value]
  query2.value.remarks = form.value.remarks
  // query2.value.addressDescs = [...form.value.addressDescList, ...addressDesc.value]
  query2.value.addressDescs = [...form.value.addressDescList]
  query2.value.statusEscription = form.value.statusEscription
  const data = query2.value
  $validateForm(form1.value, () => {
    handlingProblemPieces(data).then(res => {
      if (res.code == 200) {
        ElMessage.success('处理成功')
        cancel1()
      } else {
        ElMessage.error(res.msg)
      }
    })
  })
}
const submit2 = () => {
  // const subNos = JSON.parse(JSON.stringify(subNo.value))
  // const orderss = JSON.parse(JSON.stringify(orders.value))
  $validateForm(form2.value, () => {
    querys.value.orderNos = orders.value
    querys.value.subcontractNos = subNo.value
    querys.value.addressDescs = form.value.addressDescList
    querys.value.remarks = form.value.remarks
    querys.value.statusEscription = form.value.statusEscription
    const data = querys.value
    handlingProblemPieces(data).then(res => {
      if (res.code == 200) {
        ElMessage.success('处理成功')
        cancel2()
      } else {
        ElMessage.error(res.msg)
      }
    })
  })
}
const idss = ref([])
const subNo = ref([])
const orders = ref([])
// // 列表选择
const handleSelectionChange = (rows: { [key: string]: any }[]) => {
  subNo.value = rows.map((item) => item.subcontractNo)
  orders.value = rows.map((item) => item.orderNo)
  idss.value = rows.map((item) => item.userId)
  single.value = rows.length != 1
  multiple.value = !rows.length
}

const queryParams = ref({
  pageSize: 10,
  pageNum: 1,
  waybillNo: '',
  ladingNo: '',
  mainTransferNo: '',
  subcontractNo: '',
  customerCode: '',
  orderDate: '',
  makerAccount: '',
  statusEscription: undefined,
  feedbackStatus: '',
  transportType: '',
  beginTime: '',
  endTime: '',
  operatingDateStart: '',
  operatingDateEnd: '',
})
const fileFormatter = (fileName, fileUrlBase64) => {
  const extension = fileName.split('.')[fileName.split('.').length - 1]
  const prefix = [
    { key: 'doc', value: 'application/msword' },
    { key: 'docx', value: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' },
    { key: 'xls', value: 'application/vnd.ms-excel' },
    { key: 'xlsx', value: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' },
    { key: 'pdf', value: 'application/pdf' },
    { key: 'ppt', value: 'application/vnd.ms-powerpoint' },
    { key: 'pptx', value: 'application/vnd.openxmlformats-officedocument.presentationml.presentation' },
    { key: 'txt', value: 'text/plain' },
    { key: 'png', value: 'image/png' },
    { key: 'jpg', value: 'image/jpeg' },
    { key: 'gif', value: 'image/gif' },
    { key: 'svg', value: 'image/svg+xml' },
    { key: 'ico', value: 'image/x-icon' },
    { key: 'bmp', value: 'image/bmp' },
  ]
  prefix.forEach(el => {
    if (el.key === extension) {
      fileUrlBase64 = `data:${ el.value };base64,${ fileUrlBase64 }`
    }
  })
  return fileUrlBase64
}
// 下载索赔书
const handleDownloadClaLet = (row: { [key: string]: any }) => {
  const { id } = row
  downloadProblemPiece(id).then(res => {
    if (res.code == 200) {
      let { fileName, fileUrlBase64 } = res.data[0]
      fileUrlBase64 = proxy.fileFormatter(fileName, fileUrlBase64)
      const a = document.createElement('a')
      a.href = fileUrlBase64
      a.setAttribute('download', fileName)
      a.click()
    } else {
      ElMessage.error(res.msg)
    }
  })
}
const config = computed({
	
  get() {
    return {
      query: {
        fields: [
          {
            label: '客户单号',
            prop: 'waybillNo',
            option: {
              placeholder: '请输入客户单号',
              type: 'textarea',
            },
          },
          {
            label: '主转单号',
            prop: 'mainTransferNo',
            option: {
              type: 'textarea',
            },
          },
          {
            label: '次转单号',
            prop: 'subcontractNo',
            option: {
              type: 'textarea',
            },
          },
          {
            label: '提单号',
            prop: 'ladingNo',
            option: {
              type: 'textarea',
            },
          },
          {
            type: 'select',
            label: '客户名称',
            prop: 'customerCode',
            option: {
              dictInfo: { dict: DictDirection.客户 },
            },
          },
          {
            type: 'date-picker',
            label: '下单时间',
            prop: 'orderDate',
            option: {
              type: 'date',
              valueFormat: 'YYYY-MM-DD',
            },
          },
          {
            type: 'date-picker',
            label: '反馈时间',
            prop: 'orderDate1',
            option: {
              type: 'date',
              valueFormat: 'YYYY-MM-DD',
            },
          },
          {
            type: 'select',
            label: '反馈状态',
            prop: 'feedbackStatus',
            option: {
              dictInfo: { dict: DictDirection.运输类型 },
            },
          },
          {
            type: 'select',
            label: '运输类型',
            prop: 'transportType',
            option: {
              dictInfo: { dict: DictDirection.运输类型 },
            },
          },
        ],
        queryParams: queryParams.value,
        formOption: {},
      },
      btns: [
        {
          title: '批量处理问题件',
          disabled: multiple.value,
          type: 'success',
          icon: Edit,
          onclick: handleUpdates,
        },
        {
          title: '导出',
          directive: [['hasPermi', ['system:problemPiece:export']]],
          onclick: handleExport,
          type: 'warning',
          icon: Bottom,
        },
      ],
      table: {
        columns: [
          { type: 'selection', width: '55' },
          {
            label: '客户名称',
            prop: 'customerName',
            width: '100',
            align: 'center',
          },
          { label: '客户单号', align: 'center', prop: 'waybillNo', width: '150' },
          { label: '主转单号', align: 'center', prop: 'mainTransferNo', width: '180' },
          { label: '次转单号', align: 'center', prop: 'subcontractNo', width: '180' },
          { label: '提单号', align: 'center', prop: 'ladingNo', width: '150' },
          { label: '物流类型', align: 'center', prop: 'logisticsType' },
          { label: '状态代码', align: 'center', prop: 'statusCode', width: '120' },
          { label: '状态说明', align: 'center', prop: 'statusEscription', width: '120' },
          { label: '物流更新时间', align: 'center', prop: 'occurrenceDate', width: '120' },
          { label: '备注', align: 'center', prop: 'remarks' },
          { label: '订单下单时间', align: 'center', prop: 'orderDate', width: '100' },
          { label: '内部备注', align: 'center', prop: 'internalRemarks' },
          { label: '客户是否反馈', align: 'center', prop: 'custDesc' },
          { label: '客户反馈时间', align: 'center', prop: 'custDate', width: '120' },
          { label: '已发邮件', align: 'center', prop: 'hairEmailDate', width: '100' },
          { label: '已回邮件', align: 'center', prop: 'backEmailDate', width: '100' },
          { label: '客户资料', align: 'center', prop: 'submitDataDate', width: '120' },
          { label: '索赔书', align: 'center', prop: 'claimDate', width: '60' },
          { label: '已索赔', align: 'center', prop: 'alreadyClaimed', width: '60' },
          { label: '已ups确认', align: 'center', prop: 'confirmedUps', width: '100' },
          { label: '预计起飞日', align: 'center', prop: 'expectedSailingDate' },
          // { label: '预计开船日', prop: 'expectedSailingDate' },
          { label: '账号方确认', align: 'center', prop: 'accountConfirmation', width: '100' },
          { label: '已赔款', align: 'center', prop: 'compensationPaid', width: '60' },
          {
            label: '操作',
            align: 'center',
            width: '360',
            fixed: 'right',
            showOverflowTooltip: false,
            render(h, params) {
              const buttons = [
                {
                  title: '处理问题件',
                  icon: Edit,
                  clickFun: handleUpdate,
                },
                {
                  title: '下载索赔书',
                  icon: Download,
                  clickFun: handleDownloadClaLet,
                },
              ]
              return buttons.map((el) => h(
                ElButton,
                {
                  text: true,
                  type: 'primary',
                  icon: el.icon,
                  onClick: () => {
                    el.clickFun(params.row)
                  },
                },
                {
                  default: () => el.title,
                },
              ))
            },
          },
        ],
        event: {
          onSelectionChange: (rows) => {
            handleSelectionChange(rows)
          },
        },
      },
      api: listPiece,
      customKey: 'express/mainBusiness/oceanShipping/problemPiece',
    }
  },
  set(val) {
    return val
  },
})

</script>

<style lang="less" scoped>
/deep/.is-guttered {
  padding: 5px;
}
/* stylelint-disable-next-line selector-class-pattern */
.myScrollbar /deep/ .el-scrollbar__wrap {
  overflow-x: hidden;
  height: 200px;
  .el-scrollbar__view {
    padding-top: 10px;
    padding-bottom: 10px;
  }
}
/deep/.row {
  display: block;
  .col {
    margin: 0 20px;
    width: 80px;
  }
}
/deep/.el-radio-group {
  width: 400px;
}
</style>
